package com.sunday.pinxinghui.model.products;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.design.widget.TabLayout.Tab;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.entity.Brand;
import com.sunday.pinxinghui.entity.IndexCategory;
import com.sunday.pinxinghui.network.ApiClient;
import com.sunday.pinxinghui.widgets.SelectBrandWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.support.design.widget.TabLayout.MODE_SCROLLABLE;

/**
 * Author by Damon,  on 2018/1/5.
 */

public class ProductsListActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.tab_layout)
    TabLayout tabLayout;
    @Bind(R.id.view_pager)
    ViewPager viewPager;
    @Bind(R.id.tab1_layout)
    TabLayout tab1Layout;
    @Bind(R.id.btn_select_brand)
    TextView btnSelectBrand;

    private String parentName;
    private int parentId;//一级分类id
    private int catId;//二级分类id


    private List<String> titles = new ArrayList<>();
    private List<IndexCategory> productClassifyList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_products_list);
        ButterKnife.bind(this);
        parentName = getIntent().getStringExtra("parentName");
        parentId = getIntent().getIntExtra("parentId", 0);
        catId = getIntent().getIntExtra("catId", 0);
        titleView.setText(parentName);
        //initView();
        getTitles();
        initSortTab();
    }

    private void getTitles() {
        showLoadingDialog(0);
        Call<ResultDO<List<IndexCategory>>> call = ApiClient.getApiAdapter().getChildrenCategory(parentId);
        call.enqueue(new Callback<ResultDO<List<IndexCategory>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<IndexCategory>>> call, Response<ResultDO<List<IndexCategory>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                ResultDO<List<IndexCategory>> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }
                if (resultDO.getCode() == 0) {
                    productClassifyList.clear();
                    productClassifyList.addAll(resultDO.getResult());
                    if (!productClassifyList.isEmpty())
                        for (IndexCategory category : productClassifyList) {
                            titles.add(category.getName());
                            initView();
                        }

                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<IndexCategory>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    PagerAdapter adapter;

    private void initView() {
        tabLayout.setTabMode(MODE_SCROLLABLE);
        adapter = new PagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(MODE_SCROLLABLE);
        int page = 0;
        if (catId == 0) {
            page = 0;
        } else {
            for (int i = 0; i < productClassifyList.size(); i++) {
                if (productClassifyList.get(i).getId() == catId) {
                    page = i;
                    break;
                }
            }
        }
        viewPager.setCurrentItem(page, false);


    }

    private void initSortTab() {
        tab1Layout.addTab(tab1Layout.newTab().setText("综合排序"));
        tab1Layout.addTab(tab1Layout.newTab().setText("销量"));
        tab1Layout.addTab(tab1Layout.newTab().setText("价格"));
        tab1Layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(Tab tab) {
                sort = tab.getPosition() + 1;
                //catId = productClassifyList.get(tab.getPosition()).getId();
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onTabUnselected(Tab tab) {

            }

            @Override
            public void onTabReselected(Tab tab) {
                if (tab.getPosition() == 2) {
                    if (sort == 3) {
                        sort = 4;
                    } else if (sort == 4) {
                        sort = 3;
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
    }


    private SelectBrandWindow selectBrandWindow;
    private Integer brandId;
    private int sort = 1;
    private int oldCatId;
    private Brand selectedBrand=null;

    @OnClick(R.id.btn_select_brand)
    void selectBrand() {
        selectBrandWindow = new SelectBrandWindow(mContext, productClassifyList.get(tabLayout.getSelectedTabPosition()).getId());
        selectBrandWindow.showDropDown(btnSelectBrand);
        selectBrandWindow.setClick(new SelectBrandWindow.Click() {
            @Override
            public void click(Brand brand) {
                btnSelectBrand.setText(brand.getName());
                   /* for (int i=0;i<titles.size();i++){
                        ((ProductClassifyFragment) (fragments[i])).setBrandId(brand.getId());
                        if (fragments[i].getUserVisibleHint()){
                            ((ProductClassifyFragment) (fragments[i])).refreshData();
                        }
                    }*/
                selectedBrand = brand;
                brandId = brand.getId();
                adapter.notifyDataSetChanged();
            }
        });
    }

    public class PagerAdapter extends FragmentPagerAdapter {

        private Fragment[] fragments;

        public PagerAdapter(FragmentManager fm) {
            super(fm);
            fragments = new Fragment[titles.size()];
        }

        @Override
        public Fragment getItem(int position) {
            if (fragments[position] == null) {
                fragments[position] = ProductClassifyFragment.newInstance(sort, productClassifyList.get(position).getId());
            }
            return fragments[position];
        }

        @Override
        public int getCount() {
            return titles.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // return super.instantiateItem(container, position);
            ProductClassifyFragment fragment = (ProductClassifyFragment) super.instantiateItem(container, position);
            //Tab tab = tabs.get(position);
            if (position == viewPager.getCurrentItem()) {
                fragment.setBrandId(brandId);
                //btnSelectBrand.setText(selectedBrand!=null?selectedBrand.getName():"全部");
            } else {
                brandId = 0;
                //btnSelectBrand.setText("全部");
                fragment.setBrandId(0);
                // oldCatId = productClassifyList.get(viewPager.getCurrentItem()).getId();
            }

//            fragment.setBrandId(brandId);
            fragment.setSort(sort);
            return fragment;
        }

        public int getItemPosition(Object object) {
            return ProListFragment.PagerAdapter.POSITION_NONE;
        }
    }


}
